<script setup lang="ts">
import { ref } from 'vue'
import { useAuthStore } from '../../base/stores/auth'

// Define emits for parent component communication
const emit = defineEmits(['close', 'switchToLogin'])

const authStore = useAuthStore()

// Form data
const name = ref('')
const email = ref('')
const password = ref('')
const confirmPassword = ref('')
const agreeTerms = ref(false)

// Form validation
const errors = ref({
  name: '',
  email: '',
  password: '',
  confirmPassword: '',
  agreeTerms: '',
  form: ''
})

// Loading state
const isSubmitting = ref(false)

// Validation functions
const validateName = () => {
  if (!name.value.trim()) {
    errors.value.name = 'Name is required'
    return false
  } else if (name.value.trim().length < 2) {
    errors.value.name = 'Name must be at least 2 characters'
    return false
  }
  errors.value.name = ''
  return true
}

const validateEmail = () => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!email.value) {
    errors.value.email = 'Email is required'
    return false
  } else if (!emailRegex.test(email.value)) {
    errors.value.email = 'Please enter a valid email address'
    return false
  }
  errors.value.email = ''
  return true
}

const validatePassword = () => {
  if (!password.value) {
    errors.value.password = 'Password is required'
    return false
  } else if (password.value.length < 8) {
    errors.value.password = 'Password must be at least 8 characters'
    return false
  }
  errors.value.password = ''
  return true
}

const validateConfirmPassword = () => {
  if (!confirmPassword.value) {
    errors.value.confirmPassword = 'Please confirm your password'
    return false
  } else if (confirmPassword.value !== password.value) {
    errors.value.confirmPassword = 'Passwords do not match'
    return false
  }
  errors.value.confirmPassword = ''
  return true
}

const validateTerms = () => {
  if (!agreeTerms.value) {
    errors.value.agreeTerms = 'You must agree to Terms and Conditions'
    return false
  }
  errors.value.agreeTerms = ''
  return true
}

// Handle form submission
const handleSubmit = async () => {
  // Reset form error
  errors.value.form = ''
  
  // Validate all fields
  const isNameValid = validateName()
  const isEmailValid = validateEmail()
  const isPasswordValid = validatePassword()
  const isConfirmPasswordValid = validateConfirmPassword()
  const isTermsValid = validateTerms()
  
  if (!isNameValid || !isEmailValid || !isPasswordValid || !isConfirmPasswordValid || !isTermsValid) {
    return
  }
  
  // Submit form
  isSubmitting.value = true
  try {
    const success = await authStore.register({
      name: name.value,
      email: email.value,
      password: password.value
    })
    
    if (success) {
      emit('close')
    } else {
      errors.value.form = authStore.error
    }
  } catch (error: any) {
    errors.value.form = error.message || 'Registration failed. Please try again.'
  } finally {
    isSubmitting.value = false
  }
}

// Close modal when clicking outside
const handleBackdropClick = (e: MouseEvent) => {
  if ((e.target as HTMLElement).classList.contains('modal-backdrop')) {
    emit('close')
  }
}
</script>

<template>
  <div class="modal-backdrop" @click="handleBackdropClick">
    <div class="modal-container" @click.stop>
      <div class="modal-header">
        <h2>Create Account</h2>
        <button class="close-btn" @click="emit('close')">&times;</button>
      </div>
      
      <div class="modal-body">
        <form @submit.prevent="handleSubmit">
          <!-- Form error message -->
          <div v-if="errors.form" class="form-error form-error-message">
            {{ errors.form }}
          </div>
          
          <!-- Name field -->
          <div class="form-group">
            <label for="name" class="form-label">Full Name</label>
            <input 
              type="text" 
              id="name" 
              class="form-input" 
              v-model="name"
              @blur="validateName"
              :class="{ 'input-error': errors.name }"
              placeholder="Your full name"
            />
            <div v-if="errors.name" class="form-error">{{ errors.name }}</div>
          </div>
          
          <!-- Email field -->
          <div class="form-group">
            <label for="reg-email" class="form-label">Email</label>
            <input 
              type="email" 
              id="reg-email" 
              class="form-input" 
              v-model="email"
              @blur="validateEmail"
              :class="{ 'input-error': errors.email }"
              placeholder="your@email.com"
            />
            <div v-if="errors.email" class="form-error">{{ errors.email }}</div>
          </div>
          
          <!-- Password field -->
          <div class="form-group">
            <label for="reg-password" class="form-label">Password</label>
            <input 
              type="password" 
              id="reg-password" 
              class="form-input" 
              v-model="password"
              @blur="validatePassword"
              :class="{ 'input-error': errors.password }"
              placeholder="Create a password"
            />
            <div v-if="errors.password" class="form-error">{{ errors.password }}</div>
          </div>
          
          <!-- Confirm password field -->
          <div class="form-group">
            <label for="confirm-password" class="form-label">Confirm Password</label>
            <input 
              type="password" 
              id="confirm-password" 
              class="form-input" 
              v-model="confirmPassword"
              @blur="validateConfirmPassword"
              :class="{ 'input-error': errors.confirmPassword }"
              placeholder="Confirm your password"
            />
            <div v-if="errors.confirmPassword" class="form-error">{{ errors.confirmPassword }}</div>
          </div>
          
          <!-- Terms and conditions -->
          <div class="form-group">
            <label class="checkbox-label terms-label">
              <input type="checkbox" v-model="agreeTerms" @change="validateTerms" />
              <span>I agree to the <a href="#" target="_blank">Terms of Service</a> and <a href="#" target="_blank">Privacy Policy</a></span>
            </label>
            <div v-if="errors.agreeTerms" class="form-error">{{ errors.agreeTerms }}</div>
          </div>
          
          <!-- Submit button -->
          <button 
            type="submit" 
            class="btn btn-primary submit-btn" 
            :disabled="isSubmitting"
          >
            {{ isSubmitting ? 'Creating account...' : 'Create Account' }}
          </button>
          
          <!-- Login link -->
          <div class="login-link">
            Already have an account? 
            <a href="#" @click.prevent="emit('switchToLogin')">Log in</a>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<style scoped>
.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(3px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1100;
  animation: fadeIn 0.2s ease-out;
}

.modal-container {
  width: 90%;
  max-width: 450px;
  background-color: var(--card-background);
  border-radius: var(--border-radius-lg);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  animation: slideIn 0.3s ease-out;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  padding: var(--space-6);
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--neutral-200);
  position: sticky;
  top: 0;
  background-color: var(--card-background);
  z-index: 1;
}

.modal-header h2 {
  margin: 0;
  color: var(--text-primary);
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: var(--neutral-500);
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.close-btn:hover {
  background-color: var(--neutral-200);
  color: var(--neutral-800);
}

.modal-body {
  padding: var(--space-6);
}

.form-error-message {
  padding: var(--space-3);
  background-color: rgba(239, 68, 68, 0.1);
  border-radius: var(--border-radius);
  margin-bottom: var(--space-4);
  text-align: center;
}

.input-error {
  border-color: var(--error-500);
}

.checkbox-label {
  display: flex;
  align-items: flex-start;
  gap: var(--space-2);
  cursor: pointer;
}

.terms-label span {
  font-size: 0.9rem;
  line-height: 1.4;
}

.submit-btn {
  width: 100%;
  margin-top: var(--space-6);
  padding: var(--space-3) var(--space-4);
}

.submit-btn:disabled {
  background-color: var(--neutral-400);
  cursor: not-allowed;
}

.login-link {
  margin-top: var(--space-6);
  text-align: center;
  font-size: 0.95rem;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideIn {
  from { 
    transform: translateY(-20px);
    opacity: 0;
  }
  to { 
    transform: translateY(0);
    opacity: 1;
  }
}
</style>